let access_token = null
try {
  const value = wx.getStorageSync('access_token')
  if (value) {
    // Do something with return value
    access_token = value
  }
} catch (e) {
  // Do something when catch error
}
const setToken = token => {
  access_token = token
  wx.setStorage({
    key: 'access_token',
    data: token
  })
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const formatDistance = n => {
  console.log(n)
  if (n >= 1000) {
    return (n / 1000).toFixed(2) + '公里'
  }
  return n + '米'
}
// const api_prefix = 'https://mp.gzyisl.com/'
const api_prefix = getApp().globalData.api + '/api/youmi/'
// const api_prefix = 'http://192.168.31.136/api/youmi/'
// const api_prefix = 'https://youmi.sweim.top/api/youmi/'

// const api_prefix = 'http://gzns.lwt.com/'
var is_login = false
var login_cbs = []
const login = cb => {
  // login_cbs.push(cb)
  if (!is_login) {
    is_login = true
    wx.reLaunch({
      url: '/pages/login/account',
      success: res => {
        is_login = false
      }
    })
    return
  } else {

    return
  }
  // is_login = true
  wx.login({
    success: res1 => {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      request({
        url: 'zyy/login/thirdlogin',
        data: {
          code: res1.code,
          third_type: 1
        },

        method: 'GET',

        success: function(data) {
          is_login = false

          access_token = data.access_token;
          //保存我的店铺id
          if (data.is_store) {
            let app = getApp();
            app.globalData.my_store_id = data.store_id;
          }

          login_cbs.forEach(cb => {
            cb && cb();
          })
          login_cbs = []


        },
        fail: function(res) {},
        complete: function(res) {},
      })

    }
  })
}
let request_count = 0
const request = options => {
  options = {
    ...{
      header: {},
      data: {},
      url: '',
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      complete: null,
    },
    ...options
  }
  let cp_option = {
    ...options
  }
  let {
    success,
    complete
  } = options

  const requestSuccess = res => {
    request_count--
    if (request_count <= 0) {
      wx.hideLoading()
    }
    if (res.statusCode != 200) {
      console.log(res)
      wx.showToast({
        title: '网络请求失败',
        mask: true,
        icon: 'none',
      })
      return;
    }

    let result = res.data
    if (result.code != 200) {
      if (result.code == 401) {
        //  wx.navigateTo({
        //    url: '/pages/login/login',
        //  })
        login(() => {
          request(cp_option)
        })


        return
      }

      wx.showToast({
        title: result.msg,
        mask: true,
        icon: 'none',
        complete: () => {

        }
      })
      return
    }

    //判断是否是登录其他人账号，修改access_token
    if (options.url == (api_prefix + 'zyy/Login/accountLogin')) {
      access_token = result.data.access_token;
    }

    success && success(result.data)
  }
  const requestComplete = res => {
    // request_count--
    // if (request_count <= 0) {
    //   wx.hideLoading()
    // }

    complete && complete(res)
  }
  const requestFail = res => {
    request_count--
    if (request_count <= 0) {
      wx.hideLoading()
    }

    complete && complete(res)
  }

  options.data && (options.data.access_token = access_token)
  options.url = api_prefix + options.url
  options.success = requestSuccess
  options.complete = requestComplete
  options.fail = requestFail
  // console.log(options)
  options.header = {
    'Cookie': 'XDEBUG_SESSION=PHPSTORM'
  }

  if (options.url.indexOf('saveFormId') == -1) {
    if (request_count <= 0) {
      wx.showLoading({
        mask: true,
      })
    }
    request_count++
  } else {
    if (request_count < 0) {
      request_count = 0;
    }
  }
  wx.request(options)
}
const upload = options => {
  options = {
    ...{
      header: {},
      url: '',
      complete: null,
    },
    ...options
  }
  let cp_option = {
    ...options
  }
  let {
    success,
    complete,
  } = options
  const requestSuccess = res => {
    request_count--
    if (request_count <= 0) {
      wx.hideLoading()
    }
    if (res.statusCode != 200) {
      console.log(res)
      wx.showToast({
        title: '网络请求失败',
        mask: true,
        icon: 'none',
      })
      return;
    }
    let result = JSON.parse(res.data)

    if (result.code != 200) {
      if (result.code == 401) {
        login(() => {
          upload(cp_option)
        })
        return
      }

      wx.showToast({
        title: result.msg,
        mask: true,
        icon: 'none',
        complete: () => {

        }
      })
      return
    }
    success && success(result.data)
  }
  const requestComplete = res => {
    // request_count--
    // if (request_count <= 0) {
    //   wx.hideLoading()
    // }

    complete && complete(res)
  }
  const requestFail = res => {
    request_count--
    if (request_count <= 0) {
      wx.hideLoading()
    }

    complete && complete(res)
  }
  //需要认证并且无token
  // if (!app.globalData.access_token) {
  //   wx.navigateTo({
  //     url: '/pages/login/login',
  //   })
  //   return
  // }
  if (!options.formData) {
    options.formData = {}
  }
  options.formData.access_token = access_token
  options.url = api_prefix + options.url
  options.success = requestSuccess
  options.complete = requestComplete
  options.fail = requestFail
  // console.log(options)
  options.header = {
    'Cookie': 'XDEBUG_SESSION=PHPSTORM'
  }
  if (request_count <= 0) {
    wx.showLoading({
      mask: true,
    })
  }
  request_count++
  wx.uploadFile(options)
}

//分享封装
const shareApp = function(that, url, title, imageUrl) {
  let app = getApp();
  let store_id = app.globalData.store_id;
  let path = url ? url : '/pages/index/index';
  let options = that.options;
  if (store_id) {
    options.store_id = store_id;
    title = app.globalData.share_store_info.name;
  }

  //拼接url的参数
  var urlArgs = path + '?'
  for (var key in options) {
    var value = options[key]
    urlArgs += key + '=' + value + '&'
  }
  path = urlArgs.substring(0, urlArgs.length - 1)
  console.log(path)
  return {
    title: title ? title : null,
    path: path,
    imageUrl: imageUrl ? imageUrl : null
  }
}
const saveFormId = function(data, cb) {
  request({
    url: 'User/saveFormId',
    data: data,
    method: 'POST',
    success: data => {
      cb && cb()
    }
  })
  cb && cb()
}

const pageQuery = function(request_data = {}, data_name = '', that, reload = false) {
  request_data = {
    url: '',
    data: {},
    method: 'GET',
    success: res => {},
    ...request_data
  }
  that.data[`${data_name}CurrentPage`] = that.data[`${data_name}CurrentPage`] || 1
  that.data[`${data_name}List`] = that.data[`${data_name}List`] || []
  if (reload) {
      that.setData({
          [`${data_name}List`]: [],
          [`${data_name}NoMore`]: false
      })
  }
  request_data.data.page = reload ? 1 : that.data[`${data_name}CurrentPage`]

  let querySuccess = res => {
    wx.stopPullDownRefresh();

    let all_page = res.all_page || 0
    let data = res.list || res
    let noMore = false

    if (reload) {
      that.data[`${data_name}CurrentPage`] = 1
      that.data[`${data_name}CurrentPage`]++
        if (that.data[`${data_name}CurrentPage`] > all_page) {
          noMore = true
        }
      that.setData({
        [`${data_name}List`]: data,
        [`${data_name}NoMore`]: noMore
      })
    } else {
      that.data[`${data_name}CurrentPage`]++
        if (that.data[`${data_name}CurrentPage`] > all_page) {
          noMore = true
        }
      that.setData({
        [`${data_name}List`]: [...that.data[`${data_name}List`], ...data],
        [`${data_name}NoMore`]: noMore
      })
    }
    request_data.success && request_data.success(res)
  }

  request({
    ...request_data,
    success: querySuccess
  })
}

const toPage = function(e) {
  let { url, type }  = e.currentTarget.dataset;
  if (type == 'back') {
    wx.navigateBack()
  } else if (type == 'tab') {
    wx.switchTab({
      url: url,
    })
  } else if (type == 'redirect') {
    wx.redirectTo({
      url: url,
    })
  } else {
    wx.navigateTo({
      url: url,
    })
  }
}

const getRootPath = function(url) {
  if (!url) {
    return null;
  }
  if (url.indexOf('http') == 0) {
    return url;
  }
  return api_prefix + url
}

module.exports = {
  formatTime: formatTime,
  formatDistance,
  request,
  upload,
  setToken,
  shareApp,
  saveFormId,
  pageQuery,
  toPage,
  getRootPath,
  formatNumber
}